<?php
namespace App\Http\Controllers\Api\Activity;

use DB;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\Goods\GoodsSale;

use App\Models\Goods\GoodsStore;

use App\Models\Goods\GoodsMarktingStrategy;

use App\Models\ConfigureFunction;

use App\Models\ConfigureTagRelation;

use App\Models\ConfigureTag;

use App\Service\PromotionService;

use App\Models\Mall\MallMaster;

use App\Models\SysTag;
use Illuminate\Support\Facades\Redis;

class ActivityController extends Controller {

    //集点商品列表
    public function goods(Request $request)
    {
        $page = $request->input('page', 1);
        $rp = $request->input('rp', 5);
        $sortname = $request->input('sortname', 'timeStamp');
        $sortorder = $request->input('sortorder', 'desc');
        $id = $request->input('id',0);
        $t = $request->input('t');
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());

        if (!ebsig_is_int($id)) {
            return response()->json(['code' => 10000, 'message' => '缺少活动id']);
        }

        if (empty($t)) {
            return response()->json(['code' => 10001, 'message' => '缺少活动t']);
        }

        $pcustID = get_customer_id($session_id, $platform);

        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');

        $mallID = 1;
        $mall_area_id = 0;
        if ($is_open_choose_mall == 1) {

            $mallID = redisTransformation( Redis::get($session_id.'G_CHOOSE_MALL_ID'));
           
            if (!ebsig_is_int($mallID)) {
                return response()->json(['code' => 100003, 'message' => '请先选择门店']);
            }

            //查询门店信息
            $mall = MallMaster::getCache($mallID);
            if (!$mall) {
                return response()->json(['code' => 100004, 'message' => '门店不存在']);
            }
            $mall_area_id = $mall['mallareaID'];

        }

        if (!empty($sortname)) {
            switch ($sortname) {
                case 'price':
                    $sortname = 'salePrice';
                    break;
                case 'update':
                    $sortname = 'timeStamp';
                    break;
                case 'discount':
                    $sortname = 'discount';
                    break;
                case 'sale':
                    $sortname = 'saletotal';
                    break;
                default:
                    $sortname = 'timeStamp';
                    break;
            }
        }

        $table_name = $t . '_goods';

        $return_data = array(
            'count' => 0,
            'list' => []
        );

        $count_sql = 'SELECT COUNT(gm.mainPostID) AS c FROM (SELECT postID FROM '.$table_name.' WHERE id = '.$id.') AS T 
                      INNER JOIN goods_master gm ON gm.postID = T.postID WHERE gm.forsale = 1 AND gm.useFlg = 1';
        $count_array = DB::select($count_sql);
        $return_data['count'] = $count_array[0]['c'];
        if ($return_data['count'] == 0) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);
        }

        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        $sql = '';

        //排序
        if (!empty($sortname)) {

            if (!in_array($sortorder, array('ASC', 'DESC', 'asc', 'desc'))) {
                $sortorder = 'ASC';
            } else {
                $sortorder = strtoupper($sortorder);
            }
            $sql .= sprintf(' ORDER BY gm.%s %s', $sortname, $sortorder);

        }

        //分页
        if (!ebsig_is_int($page))
            $page = 1;
        if (!ebsig_is_int($rp)) {
            $rp = 10;
        }
        $sql .= sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);

        //查询商品数据
        $search_sql = 'SELECT gm.* FROM (SELECT postID FROM '.$table_name.' WHERE id = '.$id.') AS T 
                      INNER JOIN goods_master gm ON gm.postID = T.postID WHERE gm.forsale = 1 AND gm.useFlg = 1 ' . $sql;
        $return_data['list'] = DB::select($search_sql);

        $return_goods_data = [];

        foreach ($return_data['list'] as &$goods) {
            $goods['enableSaleAmount'] = 0;

            $goods_sale_data = GoodsSale::select('product_code','postID','product_spec','virtual_id')->where(['mainPostID'=>$goods['mainPostID'],'forsale'=>1])->get()->toArray();
            foreach($goods_sale_data as &$sale_goods) {
                $goods['virtual_id'] = $sale_goods['virtual_id'];
                $enableSaleAmount = GoodsStore::search($sale_goods['product_code'], $sale_goods['product_spec'], $mallID);
                if ( $enableSaleAmount > 0 ) {
                    $goods['enableSaleAmount'] = $enableSaleAmount;
                    $goods['postID'] = $sale_goods['postID'];
                    break;
                }
            }

            $goods['spec_num'] = count($goods_sale_data);
            $goods['link'] = set_goods_link($goods['postID']);
            $goods['wap_link'] = set_wap_goods_link($goods['postID']);
            $goods['img_link'] = $domain_url . $goods['goodsMainPic'];

            if ( $mallID > 0 ) {
                $goods_markting_strategy = GoodsMarktingStrategy::where(['shop_id' => $mallID,'postID' => $goods['postID']])->first();
                if ($goods_markting_strategy) {
                    $goods_markting_strategy = $goods_markting_strategy->toArray();
                    $goods['marketPrice'] = $goods_markting_strategy['marketPrice'];
                    $goods['salePrice'] = $goods_markting_strategy['salePrice'];
                    $goods['salePoints'] = $goods_markting_strategy['salePoints'];
                }
            }


            if ($goods['salePrice'] <= 0) {
                $return_data['list']['count'] -= 1;
                continue;
            }

            $tag_data = [];

            //商品促销查询
            $promotion_data = PromotionService::goods(array(
                'postID' => $goods['postID'],
                'salePrice' => $goods['salePrice'],
                'salePoints' => isset($goods['salePoints']) ? $goods['salePoints'] : 0,
                'product_code' => $goods['product_code'],
                'marketPrice' => $goods['marketPrice'],
                'goods_amount' => 1,
                'pcustID' => $pcustID,
                'mallareaID' => $mall_area_id,
                'mallID' => $mallID,
                'platform' => 0
            ));
            if (!isset($promotion_data['promotion']) && empty($promotion_data['promotion'])) {
                $price = $goods['salePrice'];
            } else {
                $price = $promotion_data['price'];
                foreach ($promotion_data['promotion'] as $p) {
                    if (isset($p['selected']) && $p['selected'] == 1) {
                        $res_data = SysTag::getCache($p['promotion_type']); //查询商品标签信息
                        if ($res_data) {
                            $tag_data[] = $res_data;
                        }
                    }
                }
            }

            //查询商品标签
            $tag_relation_data = ConfigureTagRelation::where(['relation_id'=>$goods['mainPostID'],'relation_type'=>1])->get()->toArray();
            if ($tag_relation_data) {
                foreach ($tag_relation_data as $tag) {
                    $reslut_data = ConfigureTag::where(['tag_id'=>$tag['tag_id']])->first();
                    if ($reslut_data) {
                        $reslut_data = $reslut_data->toArray();
                        $tag_data[] = $reslut_data;
                    }
                }
            }

            $return_goods_data[] = array(
                'mainPostID' => $goods['mainPostID'],
                'postID' => $goods['postID'],
                'goodsName' => $goods['goodsName'],
                'salePrice' => round($goods['salePrice'], 2),
                'marketPrice' => round($goods['marketPrice'], 2),
                'wap_link' => $goods['wap_link'],
                'img_link' => $goods['img_link'],
                'price' => round($price, 2),
                'enableSaleAmount' => $goods['enableSaleAmount'],
                'tag' => $tag_data,
                'spec_num' => isset($goods['spec_num']) ? $goods['spec_num'] : 0
            );
        }

        //查询购物车按钮
        $cart_btn = '';
        $cart_btn_setting_data = ConfigureFunction::getConfigure(14);
        if ( $cart_btn_setting_data ) {
            if (isset($cart_btn_setting_data['list']) && $cart_btn_setting_data['list']['is_show'] == 1) {
                $cart_btn = $cart_btn_setting_data['list']['cart_image'];
            }
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => [
            'count' => $return_data['count'],
            'cart_btn' => $cart_btn,
            'list' => $return_goods_data
        ]]);

    }

}